/**
 * @Author 天下无敌
 * @Date 
 * @AIDE AIDE+ 
 */
package com.ecs.core.gsystem.player;
import com.artemis.systems.IteratingSystem;
import com.artemis.annotations.All;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.Gdx;
import com.ecs.core.components.player.NearTagCom;
import com.artemis.ComponentMapper;
import com.ecs.core.components.attribute.Transform;
import com.ecs.core.components.draw.SpriteRender;
import com.ecs.core.components.map.TerrainCom;
import com.badlogic.gdx.math.Rectangle;

@All({NearTagCom.class})
public class PlayerTerrainStateSystem extends IteratingSystem
{
	private PlayerDataSystem player;
	private ComponentMapper<Transform> transforms;
	private ComponentMapper<SpriteRender> sprites;
	private ComponentMapper<TerrainCom> terrains;
	private int currentBlockId = -1;
	private final Rectangle entityRect = new Rectangle();
	private ShaderProgram waterShader;
	private boolean isWaterState = false;
	@Override
	protected void initialize() {
		super.initialize();
		waterShader = new ShaderProgram(
		Gdx.files.internal("Shader/playerWater.vert"),
		Gdx.files.internal("Shader/playerWater.frag")
		);
	}
	
	
	@Override
	protected void process(int p) {
		float px = player.getPlayerCenterX();
		float py = player.getPlayerCenterY();
		
		Transform tsf = transforms.get(p);
		entityRect.set(
		tsf.getPosX(),
		tsf.getPosY(),
		tsf.getScaleX(),
		tsf.getScaleY());
		
		if(entityRect.contains(px,py) && terrains.get(p) != null){
			currentBlockId = p;
		}
	}

	@Override
	protected void end() {
		super.end();
		if(currentBlockId != -1) {
            TerrainCom terrain = terrains.get(currentBlockId);
            if(terrain == null) return;

            int playerId = player.getId();
            SpriteRender playerSprite = sprites.get(playerId);

            if(terrain.isWater) {
                if(!isWaterState) {
                    // 进入水中 - 切换到自定义着色器
                    playerSprite.customShader = waterShader;
                    isWaterState = true;
                }
            } else {
                if(isWaterState) {
                    // 离开水中 - 恢复默认着色器
                    playerSprite.customShader = null;
                    isWaterState = false;
                }
            }
        }
	}


}
